package cn.edu.zju.gis.disasterBE.sever.service;

import cn.edu.zju.gis.disasterBE.sever.dao.DisasterResponseDAO;
import cn.edu.zju.gis.disasterBE.sever.entity.DisasterResponse;
import cn.edu.zju.gis.disasterBE.sever.entity.global.MyResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;

@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class DisasterResponseService {
    protected final DisasterResponseDAO disasterResponseDAO;

    public MyResponse<List<DisasterResponse>> disasterGetAll()
    {
        List<DisasterResponse> disasterResponses =disasterResponseDAO.disasterGetAll();
        MyResponse<List<DisasterResponse>> myResponse = new MyResponse<>();
        myResponse.setData(disasterResponses);
        myResponse.setState(true);
        myResponse.setMsg("Read disasters successfully");
        System.out.println("get disaster successfully");
        return myResponse;
    }

   /*
   保存灾害数据进入数据库
    */
    public MyResponse<DisasterResponse> saveDisaster(String json)
    {
        MyResponse<DisasterResponse> myResponse = new MyResponse<>();
        JSONObject jsonObject=JSON.parseObject(json);
        String start_time = jsonObject.get("start_time").toString();
        jsonObject.remove("start_time");
        //DisasterResponse disasterResponse = JSON.parseObject(json, DisasterResponse.class);
        DisasterResponse disasterResponse = JSON.parseObject(String.valueOf(jsonObject), DisasterResponse.class);
        //Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        if(start_time==null || start_time.length()==0){
            disasterResponse.setStartTime(new Timestamp(System.currentTimeMillis()-3*1000*60*60*24));
            disasterResponse.setEndTime(new Timestamp(System.currentTimeMillis()+14*1000*60*60*24));
        }
        else{
            disasterResponse.setStartTime(Timestamp.valueOf(start_time));
            disasterResponse.setEndTime(new Timestamp((disasterResponse.getStartTime().getTime()+14*1000*60*60*24)));
        }
        disasterResponse.setSponsor("ChinaGEO Disaster data response mechanism CDDR");
        myResponse.setData(disasterResponse);
        if(disasterResponseDAO.saveDisaster(disasterResponse))
        {
            myResponse.setState(true);
            myResponse.setMsg("save successfully");
        }
        else
        {
            myResponse.setMsg("Fail to save");
            myResponse.setState(false);
        }
        System.out.println("save disaster successfully");

        // search and insert the image
        int did = disasterResponseDAO.getDid(disasterResponse.getName());
        double lat = disasterResponse.getLat();
        double lng = disasterResponse.getLon();
        Timestamp beginPosition = disasterResponse.getStartTime();
        Timestamp endPosition = disasterResponse.getEndTime();
        String aoi = disasterResponse.getAoijson();
        newThreadSearch search = new newThreadSearch ( "search_thread",lat,lng,did,beginPosition,endPosition,aoi);
        search.start();

        return myResponse;
    }

    public MyResponse<List<DisasterResponse>> durableDisasterGet()
    {
        List<DisasterResponse> disasterResponses =disasterResponseDAO.durableDisasterGet();
        MyResponse<List<DisasterResponse>> myResponse = new MyResponse<>();
        myResponse.setData(disasterResponses);
        myResponse.setState(true);
        myResponse.setMsg("Read disasters successfully");
        System.out.println("get durable disaster successfully");
        return myResponse;
    }

    public MyResponse<String> endResponse(String did)
    {
        MyResponse<String> myResponse = new MyResponse<>();
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        if(disasterResponseDAO.endResponse(Integer.parseInt(did), timestamp) == 1)
        {
            myResponse.setState(true);
            myResponse.setMsg("end successfully");
            myResponse.setData(null);
        }
        else
        {
            myResponse.setState(false);
            myResponse.setData(null);
            myResponse.setMsg("Disaster doesn't exist");
        }
        System.out.println("end disaster successfully");
        return myResponse;
    }
}

class newThreadSearch implements Runnable {
    private Thread t;
    private String threadName;

    private double lat;
    private double lng;
    private int did;
    Timestamp beginPosition;
    Timestamp endPosition;
    String aoi;

    newThreadSearch( String name,double lat_in,double lng_in,int did_in, Timestamp beginPosition, Timestamp endPosition, String aoi) {
        threadName = name;
        this.lat = lat_in;
        this.lng = lng_in;
        this.did = did_in;
        this.beginPosition = beginPosition;
        this.endPosition = endPosition;
        this.aoi = aoi;
        System.out.println("Creating " +  threadName );
    }

    public void run() {
        System.out.println("Running " +  threadName );

        try {
            ImageDownService.imageSearch(lat,lng,did,beginPosition,endPosition,aoi,"0");
            ImageDownService.imageSearch(lat,lng,did,beginPosition,endPosition,aoi,"100");
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        System.out.println("Thread " +  threadName + " exiting.");
    }

    public void start () {
        System.out.println("Starting " +  threadName );
        if (t == null) {
            t = new Thread (this, threadName);
            t.start ();
        }
    }
}
